<template>
<div class="common-layout">
    <el-container>
        <el-header>
            <el-button @click="logout" type="danger" round>退出登录</el-button>
            <el-button @click="viewUserAnalysis" type="warning" round>查看用户分析</el-button>
            <el-button @click="viewMenu" type="success" round>查看菜品列表</el-button>
        </el-header>

        <el-main>
            <el-row>
                <el-col :span="12">
                    <h3>商户列表</h3>
                    <el-button type="primary" @click="showAddMerchantDialog">添加商户</el-button>
                    <el-table :data="MerchantList" height="520" style="width: 100%">
                        <el-table-column prop="merchant_name" label="商户名称" width="180" />
                        <el-table-column prop="merchant_ID" label="商户ID" width="180" />
                        <el-table-column prop="address" label="地址" />
                        <el-table-column label="操作">
                            <template #default="scope">
                                <el-button size="small" @click="EditMerchant(scope.$index, scope.row)">
                                修改
                                </el-button>
                                <el-button size="small" type="danger" @click="DeleteMerchant(scope.$index, scope.row)">
                                删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                </el-col>

                <el-col :span="12">
                    <h3>用户列表</h3>
                    <el-button type="primary" @click="showAddUserDialog">添加用户</el-button>
                    <el-table :data="getPaginatedUserList()" height="520" style="width: 100%">
                        <el-table-column prop="user_name" label="姓名" width="100" />
                        <el-table-column prop="user_ID" label="用户ID" width="180" />
                        <el-table-column prop="studentOrWorkNumber" label="学号/工号" />
                        <el-table-column prop="role" label="角色" />
                        <el-table-column label="操作" width="180">
                            <template #default="scope">
                                <el-button size="small" @click="EditUser(scope.$index, scope.row)">
                                修改
                                </el-button>
                                <el-button size="small" type="danger" @click="DeleteUser(scope.$index, scope.row)">
                                删除
                                </el-button>
                            </template>
                        </el-table-column>
                    </el-table>
                    <el-pagination
                    :current-page="currentPage"
                    :page-size="pageSize"
                    layout="total, prev, pager, next"
                    :total="UserList.length"
                    @current-change="handlePageChange"
                    ></el-pagination>   
                </el-col>
            </el-row>
        </el-main>

        <!-- 修改商户对话框 -->
        <el-dialog v-model="editMerchantDialogVisible" title="修改商户">
            <el-form :model="editMerchantForm">
                <el-form-item label="商户名称">
                    <el-input v-model="editMerchantForm.merchant_name"></el-input>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="editMerchantForm.address"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="editMerchantForm.password" type="password"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="editMerchantDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="updateMerchant">确认</el-button>
            </div>
        </el-dialog>

        <!-- 添加商户对话框 -->
        <el-dialog v-model="addMerchantDialogVisible" title="添加商户">
            <el-form :model="addMerchantForm">
                <el-form-item label="商户名称">
                    <el-input v-model="addMerchantForm.merchant_name"></el-input>
                </el-form-item>
                <el-form-item label="地址">
                    <el-input v-model="addMerchantForm.address"></el-input>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="addMerchantForm.password" type="password"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addMerchantDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addMerchant">确认</el-button>
            </div>
        </el-dialog>

        <!-- 添加用户对话框 -->
        <el-dialog v-model="addUserDialogVisible" title="添加用户">
            <el-form :model="addUserForm">
                <el-form-item label="姓名">
                    <el-input v-model="addUserForm.user_name"></el-input>
                </el-form-item>
                <el-form-item label="性别">
                    <el-select v-model="addUserForm.gender" placeholder="选择性别">
                        <el-option label="男" :value="0"></el-option>
                        <el-option label="女" :value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="学号/工号">
                    <el-input v-model="addUserForm.studentOrWorkNumber"></el-input>
                </el-form-item>
                <el-form-item label="年龄">
                    <el-input v-model="addUserForm.age"></el-input>
                </el-form-item>
                <el-form-item label="角色">
                    <el-select v-model="addUserForm.role" placeholder="选择角色">
                        <el-option label="学生" :value="0"></el-option>
                        <el-option label="教职工" :value="1"></el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="密码">
                    <el-input v-model="addUserForm.password" type="password"></el-input>
                </el-form-item>
            </el-form>
            <div slot="footer" class="dialog-footer">
                <el-button @click="addUserDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="addUser">确认</el-button>
            </div>
        </el-dialog>
    </el-container>
</div>
</template>

<script setup>
import axios from '@/axios'
import { ref, onMounted } from 'vue';
import { ElMessage } from 'element-plus';
import router from '@/router';

const MerchantList = ref([]);
const UserList = ref([]);
const currentPage = ref(1);  // 当前的页码
const pageSize = ref(10);  // 每页显示的用户数量

const editMerchantDialogVisible = ref(false);  // 修改商户对话框是否可见
const addMerchantDialogVisible = ref(false);   // 添加商户对话框是否可见
const addUserDialogVisible = ref(false);       // 添加用户对话框是否可见

const editMerchantForm = ref({
    merchant_name: '',
    address: '',
    password: '',
});
const addMerchantForm = ref({
    merchant_name: '',
    address: '',
    password: '',
});
const addUserForm = ref({
    user_name: '',
    gender: '',
    studentOrWorkNumber: '',
    age: '',
    role: '',
    password: '',
});

/* 从后端获取数据 */
const fetchMerchantList = async () => {
  try {
    const response = await axios.get('/api/admin/GetMerchantList'); 
    MerchantList.value = response.data;
  } catch (error) {
    console.error('Error fetching merchant list:', error);
  }
};

const fetchUserList = async () => {
  try {
    const response = await axios.get('/api/admin/GetUserList'); 
    UserList.value = response.data;
  } catch (error) {
    console.error('Error fetching user list:', error);
  }
};

/* 修改商户信息 */
const EditMerchant = (index, row) => {
  editMerchantForm.value = { ...row };
  editMerchantDialogVisible.value = true;
};
const updateMerchant = async () => {
    if (!editMerchantForm.value.merchant_name || !editMerchantForm.value.password) {
        ElMessage({
            type: 'error',
            message: '请填写必填项'
        });
        return;
    }

    try {
        await axios.put(`/api/admin/updateMerchant/${editMerchantForm.value.merchant_ID}`, {
            merchant_name: editMerchantForm.value.merchant_name,
            address: editMerchantForm.value.address,
            password: editMerchantForm.value.password,
        });
        ElMessage({
            type: 'success',
            message: '修改成功'
        });
        fetchMerchantList();  // 重新获取商户列表
        editMerchantDialogVisible.value = false;
    } catch (error) {
        console.error('Error updating merchant:', error);
        ElMessage({
            type: 'error',
            message: '修改失败'
        });
    }
};

/* 删除商户 */
const DeleteMerchant = async(index, row) => {
  try {
    // 发送请求到后端删除商户
    await axios.post(`/api/admin/DeleteMerchant/${row.merchant_ID}`);
    // 从商户列表中删除该商户
    MerchantList.value.splice(index, 1);
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
  } catch (error) {
    console.error('Error deleting merchant:', error);
    ElMessage({
      type: 'error',
      message: '删除失败',
    });
  }
};

/* 修改用户信息 */
const EditUser = (index, row) => {
    router.push(`/edit_user/${row.user_ID}`);
};

/* 删除用户 */
const DeleteUser = async(index, row) => {
  try {
    // 发送请求到后端删除用户
    await axios.post(`/api/admin/DeleteUser/${row.user_ID}`);
    // 从用户列表中删除该用户
    UserList.value.splice(index, 1);
    ElMessage({
      type: 'success',
      message: '删除成功',
    });
  } catch (error) {
    console.error('Error deleting user:', error);
    ElMessage({
      type: 'error',
      message: '删除失败',
    });
  }
};

/* 添加商户 */
const showAddMerchantDialog = () => {
    addMerchantDialogVisible.value = true;
};
const addMerchant = async () => {
    if (!addMerchantForm.value.merchant_name || !addMerchantForm.value.password) {
        ElMessage({
            type: 'error',
            message: '请填写必填项'
        });
        return;
    }

    try {
        await axios.post(`/api/admin/AddMerchant`, {
            merchant_name: addMerchantForm.value.merchant_name,
            address: addMerchantForm.value.address,
            password: addMerchantForm.value.password,
        });
        ElMessage({
            type: 'success',
            message: '添加成功'
        });
        fetchMerchantList();  // 重新获取商户列表
        addMerchantDialogVisible.value = false;
        addMerchantForm.value = { merchant_name: '', address: '', password: '' };  // 清空表单
    } catch (error) {
        console.error('Error adding merchant:', error);
        ElMessage({
            type: 'error',
            message: '添加失败'
        });
    }
};

/* 添加用户 */
const showAddUserDialog = () => {
    addUserDialogVisible.value = true;
};

const addUser = async () => {
    if (!addUserForm.value.user_name || !addUserForm.value.studentOrWorkNumber || !addUserForm.value.age || !addUserForm.value.password) {
        ElMessage({
            type: 'error',
            message: '请填写必填项'
        });
        return;
    }
    try {
        await axios.post(`/api/admin/AddUser`, {
            user_name: addUserForm.value.user_name,
            gender: addUserForm.value.gender,
            studentOrWorkNumber: addUserForm.value.studentOrWorkNumber,
            age: addUserForm.value.age,
            role: addUserForm.value.role,
            password: addUserForm.value.password,
        });
        ElMessage({
            type: 'success',
            message: '添加成功'
        });
        fetchUserList();  // 重新获取用户列表
        addUserDialogVisible.value = false;
        addUserForm.value = { user_name: '', gender: '', studentOrWorkNumber: '', age: '', role: '', password: '' };
    } catch (error) {
        console.error('Error adding user:', error);
        ElMessage({
            type: 'error',
            message: '添加失败'
        });
    }
};

/* 分页处理：根据当前页码和每页大小来计算分页后的用户列表数据 */
const getPaginatedUserList = () => {
  const start = (currentPage.value - 1) * pageSize.value;
  const end = start + pageSize.value;
  return UserList.value.slice(start, end);
};

const handlePageChange = (page) => {
  currentPage.value = page;
};

/* 在组件挂载后立即调用 fetchMerchantList 和 fetchUserList 函数 */
onMounted(() => {
  fetchMerchantList();
  fetchUserList();
});

/* 退出登录 */
const logout = () => {
    router.push('/');
};

/* 查看用户分析 */
const viewUserAnalysis = () => {
    router.push('/user_analysis');
};

/* 查看菜品列表 */
const viewMenu = () => {
    router.push('/admin_menu');
};
</script>

<style scoped>

</style>
  